package com.hp.weather.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hp.weather.common.Constant;
import com.hp.weather.entity.Result;
import com.hp.weather.entity.Weather;
import com.hp.weather.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

import static com.hp.weather.common.Constant.WEATHER_REDIS_KEY_PREFIX;


/**
 * @author Administrator
 */
@Service
@Slf4j
public class WeatherServiceImpl implements WeatherService {

    public static final String SUCCESS_STATUS = "success";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${baidu.weather.ak}")
    private String ak;

    @Override
    public Weather getWeatherDataByLocation(String location) {
        String jsonStr;
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        boolean hasKey = stringRedisTemplate.hasKey(WEATHER_REDIS_KEY_PREFIX + location);

        if (hasKey) {
            log.info("from cache data ...");
             jsonStr = operations.get(WEATHER_REDIS_KEY_PREFIX + location);

        } else {
            log.info("from baidu data ...");
            jsonStr = restTemplate.getForObject(Constant.WEATHER_URL, String.class,location,ak);
            operations.set(WEATHER_REDIS_KEY_PREFIX + location, jsonStr, 1L, TimeUnit.HOURS);
        }
        Result res = JSONObject.parseObject(jsonStr, Result.class);
        if (res == null || !SUCCESS_STATUS.equals(res.getStatus())) {
            log.error("======百度天气数据获取失败 ...");
            return new Weather();
        }
        return res.getResults().get(0);
    }
}
